unit libSysFunctionU;

interface

uses
  Classes, FireDAC.Comp.Client, SysUtils;

type
  TSysFunction = Class(TInterfacedObject)
  private
    FDataSet: TFDQuery;
    FLocationControl: integer;
    function GetLocationControl: integer;
  protected
    class function AccessInstance(Request: integer): TSysFunction;
    constructor CreateInstance;
  public
    constructor Create;
    destructor Destroy; override;
    class function Instance: TSysFunction;
    class procedure ReleaseInstance;
  published
    property LocationControl: integer
      read FLocationControl;
  End;

implementation

uses
  libParamsU, MainModule;

{ TSysFunction }

{------------------------------------------------------------------------------}
class function TSysFunction.AccessInstance(Request: integer): TSysFunction;
  {$j+}
  const FInstance: TSysFunction = nil;
  {$j-}
begin
  case Request of
    0:;
    1: if not Assigned(FInstance) then FInstance := CreateInstance;
    2: FInstance := nil;
    else
      raise Exception.CreateFmt('Illegal request %d in AccessInstance', [request]);
  end;
  Result := FInstance;
end;

{------------------------------------------------------------------------------}
constructor TSysFunction.Create;
begin
  inherited Create;
  raise Exception.CreateFmt('Access class %s through instance only', [ClassName]);
end;

{------------------------------------------------------------------------------}
constructor TSysFunction.CreateInstance;
begin
  inherited Create;
  FDataSet := TFDQuery.Create(nil);
  FDataSet.Connection := UniMainModule.FDConnection;

  FLocationControl := GetLocationControl;
end;

{------------------------------------------------------------------------------}
destructor TSysFunction.Destroy;
begin
  if Assigned(FDataSet) then
    FDataSet.Free;
  if AccessInstance(0) = self then AccessInstance(2);
  inherited;
end;

{------------------------------------------------------------------------------}
function TSysFunction.GetLocationControl: integer;
begin
  Result := -1;
  FDataSet.Close;
  FDataSet.SQL.Text := 'select fldLocationControl from tblUser '
    + ' where fldUserCode = ' + QuotedStr(sUserCode);
  try
    FDataSet.Open;
    if FDataSet.RecordCount > 0 then
      Result := FDataSet['fldLocationControl'];
  finally
    FDataSet.Close;
  end;
end;

{------------------------------------------------------------------------------}
class function TSysFunction.Instance: TSysFunction;
begin
  Result := AccessInstance(1);
end;

{------------------------------------------------------------------------------}
class procedure TSysFunction.ReleaseInstance;
begin
  AccessInstance(0).Free;
end;

end.
